using B.S.XZYData.Api.Wrter.Application.Command.AssemblyWorkOrder;
using B.S.XZYData.Domain.ZSHH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace B.S.XZYData.Api.Wrter.Application.Handler.AssemblyWorkOrder
{
    /// <summary>
    /// 打印装配工单处理器
    /// </summary>
    public class PrintAssemblyWorkOrderHandler : IRequestHandler<PrintAssemblyWorkOrderCommand, ApiResult<PrintAssemblyWorkOrderResponseDto>>
    {
        private readonly IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> _assemblyWorkOrderRepo;
        private readonly IBaseRepository<AssemblyWorkOrderProductDetail> _productDetailRepo;
        private readonly ILogger<PrintAssemblyWorkOrderHandler> _logger;

        public PrintAssemblyWorkOrderHandler(
            IBaseRepository<Domain.ZSHH.AssemblyWorkOrder> assemblyWorkOrderRepo,
            IBaseRepository<AssemblyWorkOrderProductDetail> productDetailRepo,
            ILogger<PrintAssemblyWorkOrderHandler> logger)
        {
            _assemblyWorkOrderRepo = assemblyWorkOrderRepo;
            _productDetailRepo = productDetailRepo;
            _logger = logger;
        }

        public async Task<ApiResult<PrintAssemblyWorkOrderResponseDto>> Handle(PrintAssemblyWorkOrderCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<PrintAssemblyWorkOrderResponseDto>();
            try
            {
                // 查询装配工单
                var workOrder = await _assemblyWorkOrderRepo.GetValue(request.Id);
                if (workOrder == null)
                {
                    res.Msg = "装配工单不存在";
                    res.Code = ApiEnum.Fail;
                    return await System.Threading.Tasks.Task.FromResult(res);
                }

                // 查询关联的产品明细
                var productDetails = _productDetailRepo.GetAll()
                    .Where(x => !x.IsDeleted && x.WorkOrderId == request.Id)
                    .OrderBy(x => x.HierarchyNumber)
                    .ToList();

                // 构建打印响应数据
                var printResponse = new PrintAssemblyWorkOrderResponseDto
                {
                    WorkOrder = new AssemblyWorkOrderPrintInfoDto
                    {
                        Id = workOrder.Id,
                        DocumentNumber = workOrder.DocumentNumber,
                        WorkOrderCount = workOrder.WorkOrderCount,
                        CompletedWorkOrderCount = workOrder.CompletedWorkOrderCount,
                        DocumentProgress = workOrder.DocumentProgress,
                        Remarks = workOrder.Remarks,
                        Creator = workOrder.Creator,
                        CreatorDate = workOrder.CreatorDate,
                        Updator = workOrder.Updator,
                        UpdatorDate = workOrder.UpdatorDate
                    },
                    ProductDetails = productDetails.Select(detail => new ProductDetailPrintInfoDto
                    {
                        Id = detail.Id,
                        HierarchyNumber = detail.HierarchyNumber,
                        ProductNumber = detail.ProductNumber,
                        ProductName = detail.ProductName,
                        ProductSpecification = detail.ProductSpecification,
                        WorkOrderDetailNumber = detail.WorkOrderDetailNumber,
                        Quantity = detail.Quantity,
                        CompletedQuantity = detail.CompletedQuantity,
                    }).ToList()
                };

                res.Data = printResponse;
                res.Code = ApiEnum.Success;
                res.Msg = "获取打印数据成功";

                return await System.Threading.Tasks.Task.FromResult(res);
            }
            catch (Exception ex)
            {
                _logger.LogError($"获取装配工单打印数据异常：{ex.Message}");
                res.Msg = "获取装配工单打印数据异常：" + ex.Message;
                res.Code = ApiEnum.Error;
                return await System.Threading.Tasks.Task.FromResult(res);
            }
        }
    }
} 